import React, { PureComponent } from 'react';
import { formatMessage } from 'umi';
import { Layout, message } from 'antd';
import Animate from 'rc-animate';
import { connect } from 'umi';
import { history } from 'umi';
import { eventTrack } from '@/utils/track';
import moment from 'moment';
import GlobalHeader from '@/components/GlobalHeader';
import TopNavHeader from '@/components/TopNavHeader';

import styles from './Header.less';

const { Header } = Layout;

class HeaderView extends PureComponent {
    state = {
        visible: true
    };

    static getDerivedStateFromProps(props, state) {
        if (!props.autoHideHeader && !state.visible) {
            return {
                visible: true
            };
        }
        return null;
    }

    componentDidMount() {
        document.addEventListener('scroll', this.handScroll, { passive: true });

        // 判断今天是否上报
        if (localStorage.getItem('eventTrackLogin') !== moment(new Date()).format('YYYY-MM-DD')) {
            // 埋点
            eventTrack({ eventName: 'login_click', loginStatus: 0 });
            localStorage.setItem('eventTrackLogin', moment(new Date()).format('YYYY-MM-DD'));
        }
    }

    componentWillUnmount() {
        document.removeEventListener('scroll', this.handScroll);
    }

    getHeadWidth = () => {
        const { isMobile, collapsed, setting } = this.props;
        const { fixedHeader, layout } = setting;
        if (isMobile || !fixedHeader || layout === 'topmenu') {
            return '100%';
        }
        return collapsed ? 'calc(100% - 80px)' : 'calc(100% - 256px)';
    };

    handleNoticeClear = type => {
        message.success(
            `${formatMessage({
                id: 'component.noticeIcon.cleared'
            })} ${formatMessage({
                id: `component.globalHeader.${type}`
            })}`
        );
        const { dispatch } = this.props;
        dispatch({
            type: 'global/clearNotices',
            payload: type
        });
    };

    handleMenuClick = ({ key }) => {
        const { dispatch } = this.props;
        if (key === 'logout') {
            eventTrack({
                eventName: 'portal_personal_my_exit_account_click',
                pageName: 'personal_portal'
            });
            dispatch({
                type: 'login/logout'
            });
            return;
        }
        const pathMap = {
            userCenter: '/account/center',
            triggerError: '/exception/trigger',
            userinfo: '/account/settings/base',
            passwordSettings: '/personalCenter/passwordSettings',
            myInfo: '/personal/myInfo',
            feedbackList: '/personal/feedbacks'
        };
        const path = pathMap[key];

        const eventMap = {
            myInfo: 'portal_personal_my_info_click',
            passwordSettings: 'portal_personal_my_set_password_click',
            feedbackList: 'portal_personal_my_feedback_list_click'
        };

        if (eventMap[key]) {
            eventTrack({
                eventName: eventMap[key],
                pageName: 'personal_portal'
            });
        }

        if (path) {
            history.push({ pathname: path, state: { tabRoute: true } });
        }
    };

    handleNoticeVisibleChange = visible => {
        if (visible) {
            const { dispatch } = this.props;
            dispatch({
                type: 'global/fetchNotices'
            });
        }
    };

    // 这个方法好像没被执行，也看不懂干嘛用的
    handScroll = () => {
        const { autoHideHeader } = this.props;
        const { visible } = this.state;
        if (!autoHideHeader) {
            return;
        }
        const scrollTop = document.body.scrollTop + document.documentElement.scrollTop;
        if (!this.ticking) {
            this.ticking = true;
            requestAnimationFrame(() => {
                if (this.oldScrollTop > scrollTop) {
                    this.setState({
                        visible: true
                    });
                } else if (scrollTop > 300 && visible) {
                    this.setState({
                        visible: false
                    });
                } else if (scrollTop < 300 && !visible) {
                    this.setState({
                        visible: true
                    });
                }
                this.oldScrollTop = scrollTop;
                this.ticking = false;
            });
        }
    };

    render() {
        const { isMobile, handleMenuCollapse, setting } = this.props;
        const { navTheme, layout, fixedHeader } = setting;
        const { visible } = this.state;
        const isTop = layout === 'topmenu';
        const width = this.getHeadWidth();
        const HeaderDom = visible ? (
            <Header
                style={{ padding: 0, width, position: 'relative', zIndex: 1 }}
                className={fixedHeader ? styles.fixedHeader : ''}
            >
                {isTop && !isMobile ? (
                    <TopNavHeader
                        theme={navTheme}
                        mode="horizontal"
                        onCollapse={handleMenuCollapse}
                        onNoticeClear={this.handleNoticeClear}
                        onMenuClick={this.handleMenuClick}
                        onNoticeVisibleChange={this.handleNoticeVisibleChange}
                        onClick={() => {
                            eventTrack({
                                eventName: 'portal_personal_my_click',
                                pageName: 'personal_portal'
                            });
                        }}
                        {...this.props}
                    />
                ) : (
                    <GlobalHeader
                        onCollapse={handleMenuCollapse}
                        onNoticeClear={this.handleNoticeClear}
                        onMenuClick={this.handleMenuClick}
                        onNoticeVisibleChange={this.handleNoticeVisibleChange}
                        {...this.props}
                    />
                )}
            </Header>
        ) : null;
        return (
            <Animate component="" transitionName="fade">
                {HeaderDom}
            </Animate>
        );
    }
}

export default connect(({ user, global, setting, loading }) => ({
    currentUser: user.currentUser,
    collapsed: global.collapsed,
    fetchingNotices: loading.effects['global/fetchNotices'],
    notices: global.notices,
    setting
}))(HeaderView);
